import type { App, Directive, DirectiveBinding } from 'vue'
import { ElLoading } from 'element-plus'
import { utc2BJ } from '../date'

function timeHandler(el: Element, binding: DirectiveBinding) {
  const { value, modifiers, arg } = binding
  let format = 'YYYY/MM/DD'
  if (modifiers.YMDHMS) {
    format = 'YYYY/MM/DD HH:mm:ss'
  }
  if (modifiers.YMDHM) {
    format = 'YYYY/MM/DD HH:mm'
  }
  if (modifiers.YMDH) {
    format = 'YYYY/MM/DD HH'
  }
  if (modifiers.YMD) {
    format = 'YYYY/MM/DD'
  }
  if (modifiers.Y) {
    format = 'YYYY'
  }
  if (arg === '-') {
    format.replaceAll('/', '-')
  }
  // dom对象获取自定义属性
  if (value) {
    el.innerHTML = utc2BJ(value, format)
  }
  else {
    el.innerHTML = '--'
  }
}

function enterHandler(el: Element, binding: DirectiveBinding) {
  const { value } = binding
  if (value) {
    el.innerHTML = value.enter()
  }
}

const obj: Record<string, Directive<Element, any, string, string>> = {
  time: {
    mounted: timeHandler,
    updated: timeHandler,
  },
  enter: {
    mounted: enterHandler,
    updated: enterHandler,
  },
}

export default {
  install: (app: App) => {
    app.directive('loading', ElLoading.directive)
    Object.keys(obj).forEach((key) => {
      app.directive(key, obj[key])
    })
  },
}
